<?php
namespace app\interfaces\controller;

use app\interfaces\model\MerchantMember as MemberModel;
use app\interfaces\model\MerchantShop as ShopModel;
use app\interfaces\model\ShopHome as ShopHomeModel;
use app\interfaces\model\ShopType as ShopTypeModel;
use app\interfaces\model\MemberOrder as MemberOrderModel;
use think\Db;
use think\Request;
use think\Cache;
use think\Loader;
use think\Exception;

class MerchantMember
{
    /*
     * 商家端 - 注册
     * @param  string $username 手机号
     * @param  string $password 密码
     * @param  string $code     验证码
     */
    public function register()
    {
        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];

        // 获取参数
        $data = Request::instance()->param();

        if (empty($data['username']) || empty($data['password']) || empty($data['code'])) throw new Exception('not Empty');

        // 验证
        $validate = Loader::validate('Member');
        if (!$validate->scene('create')->check($data)) return ['code' => 402, 'message' => $validate->getError()];
        //
        // 判断验证码是否正确
        $smsVerify = Cache::get('sms_verify_reg_' . $data['username']);

        if ($smsVerify != $data['code']) {
            return ['code' => 401, 'message' => '验证码错误'];
        }

        // 提交数据
        $model = new MemberModel();

        // 注册成功之后status 为 0
        $data['status'] = 0;

        $result = $model->allowField(true)->save($data);

        if ($result) {
            return ['code' => 200, 'message' => '成功', 'data' => ['user_id' => $model->id]];
        }

        return ['code' => 403, 'message' => '网络繁忙'];


    }

    /*
     * 商家端 - 登录
     * @param  string $username 手机号
     * @param  string $password 密码
     */
    public function login()
    {
        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];

        // 获取参数
        $username = Request::instance()->param('username');
        $password = Request::instance()->param('password', '', 'mcs');

        if (empty($username) || empty($password)) throw new Exception('not Empty');

        // 验证数据
        $model = new MemberModel();
        $shop_id = $model->where(['username' => $username, 'password' => $password])->value('id');

        if ($shop_id) {

            // 读取店铺信息
            $find = ShopModel::where(['member_id' => $shop_id])->field('status,reason,name')->find();

            // 如果不存在

            // if(empty($find['name'])){
            //     $find['status'] = '4';
            //     $find['reason'] = '';
            // }

            if (empty($find)) {
                $find['status'] = '0';
                $find['reason'] = '';
            } else {
                if (empty($find['name'])) {
                    $find['status'] = '4';
                    $find['reason'] = '';
                }
            }


            return ['code' => 200, 'message' => '成功', 'data' => ['user_id' => $shop_id, 'status' => $find['status'], 'reason' => $find['reason']]];
        }

        return ['code' => 401, 'message' => '账号或密码错误'];

    }

    /*
     * 商家端 - 找回密码
     * @param  string $username 手机号
     * @param  string $password 密码
     */
    public function retrieve()
    {
        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];

        // 获取参数
        $username = Request::instance()->param('username');
        $password = Request::instance()->param('password', '', 'mcs');

        if (empty($username) || empty($password)) throw new Exception('not Empty');

        $model = new MemberModel();
        // 验证数据
        $result = $model->save(['password' => $password], ['username' => $username]);

        if ($result) {
            return ['code' => 200, 'message' => '成功'];
        }

        return ['code' => 401, 'message' => '失败'];

    }

    /*
     * 商家端 - 提交认证信息
     * @param  string $shop_id      店铺ID
     * @param  string $type         分类
     * @param  string $name         名称
     * @param  string $number_id    身份证号
     * @param  string $picUrl       法人身份证照片 / 身份证照片
     * @param  string $company_img  公司营业执照 / 个人半身照
     */
    public function create_auth()
    {
        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];

        // 获取参数
        $data = Request::instance()->param();

        if (empty($data['shop_id']) || empty($data['type']) || empty($data['name']) || empty($data['number_id'])) throw new Exception('not Empty');

        $data['picUrl'] = uploadImg('picUrl', 'shop');
        $data['company_img'] = uploadImg('company_img', 'shop');

        $model = new ShopModel();
        // 验证数据
        // 修改 如果认证成功 status = 3
        $data['status'] = 3;
        $result = $model->allowField(true)->save($data, ['member_id' => $data['shop_id']]);

        if ($result) {
            return ['code' => 200, 'message' => '成功'];
        }

        return ['code' => 401, 'message' => '失败'];

    }

    /*
     * 商家端 - 店铺分类
     */
    public function shop_type()
    {

        // 读取数据
        $model = new ShopTypeModel();

        $result = $model->where(['status' => '1'])->field('id,title')->order(['sort' => 'asc', 'id' => 'asc'])->select();

        return ['code' => 200, 'message' => '成功', 'data' => $result];


    }

    /*
     * 商家端 - 创建店铺
     * @param  string $shop_id      店铺ID
     * @param  string $title        店铺名称
     * @param  string $logo         店铺LOGO
     * @param  string $type_id      店铺分类id
     */
    public function create_store()
    {
        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];

        // 获取参数
        $data = Request::instance()->param();

        if (empty($data['shop_id']) || empty($data['title']) || empty($data['type_id'])) throw new Exception('not Empty');

        $model = new ShopModel();

        // 验证数据
        $validate = Loader::validate('Shop');
        if (!$validate->check($data)) return ['code' => 401, 'message' => '店铺名重复'];

        $result = $model->allowField(true)->save($data);

        if ($result) {
            return ['code' => 200, 'message' => '成功'];
        }

        return ['code' => 401, 'message' => '创建失败'];

    }

    /*
     * 商家端 - 我的店铺
     * @param  string $shop_id      店铺ID
     */
    public function my_shop()
    {

        // 获取参数
        $shop_id = Request::instance()->param('shop_id');

        if (empty($shop_id)) throw new Exception('not Empty');

        // 读取数据
        $model = new ShopModel();

        $result = $model->where(['member_id' => $shop_id])->field('banner,logo,title')->find();

        if (empty($result)) return ['code' => 401, 'message' => '您还未开店,请先申请开店'];

        // 订单model
        $order_model = new MemberOrderModel();

        // 今日成交总额
        $result['today_volume'] = $order_model->where(['shop_id' => $shop_id, 'status' => ['not in', '0,5,6,7']])
            ->whereTime('pay_time', 'today')
            ->count();

        // 今日订单数
        $result['today_order'] = $order_model->where(['shop_id' => $shop_id, 'status' => ['not in', '5,6,7']])
            ->whereTime('create_time', 'today')
            ->count();

        // 统计model
        $home_model = new ShopHomeModel();

        // 每日访问量
        $result['visitor_volume'] = $home_model->where(['member_id' => $shop_id])->value('visitor_volume');

        $result['evaluate_status'] = Db::view('shop_goods', 'id,member_id')
            ->view('shop_goods_evaluate', 'goods_id,examine', 'shop_goods.id = shop_goods_evaluate.goods_id')
            ->where(['member_id' => $shop_id, 'examine' => '2'])
            ->count();

        return ['code' => 200, 'message' => '成功', 'data' => $result];

    }

    /*
     * 商家端 - 店铺信息
     * @param  string $shop_id    店铺ID
     */
    public function shop_view()
    {

        // 获取参数
        $shop_id = Request::instance()->param('shop_id');

        if (empty($shop_id)) throw new Exception('not Empty');

        // 读取数据
        $model = new ShopModel();

        $result = $model->where(['member_id' => $shop_id])
            ->field('logo,title,type,type_id,description,ship_address,refund_address,bank_name,cardholder_name,cardholder_number,type_id as type_name')
            ->find();

        if (empty($result)) return ['code' => 401, 'message' => '您还未开店,请先申请开店'];

        return ['code' => 200, 'message' => '成功', 'data' => $result];


    }

    /*
     * 商家端 - 更新logo
     * @param  string $shop_id  唯一标示
     * @param  string $logo     LOGO文件流
     */
    public function logo_update()
    {

        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];

        // 获取参数
        $shop_id = Request::instance()->param('shop_id');

        if (empty($shop_id)) throw new Exception('not Empty');

        $logo = uploadImg('logo', 'shop');

        $model = new ShopModel();
        // 验证数据
        $result = $model->save(['logo' => $logo], ['member_id' => $shop_id]);

        if ($result) {
            return ['code' => 200, 'message' => '成功', 'data' => $logo];
        }

        return ['code' => 401, 'message' => '网络繁忙'];

    }

    /*
     * 商家端 - 更新其他字段
     * @param  string $shop_id 唯一标示
     */
    public function field_update()
    {

        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];

        // 获取参数
        $data = Request::instance()->param();

        if (empty($data['shop_id'])) throw new Exception('not Empty');

        $model = new ShopModel();
        // 验证数据
        $result = $model->allowField(true)->save($data, ['member_id' => $data['shop_id']]);

        if ($result) {
            return ['code' => 200, 'message' => '成功'];
        }

        return ['code' => 401, 'message' => '网络繁忙'];

    }

    /*
     * 商家端 - 更新密码
     * @param  string $user_id 会员ID
     * @param  string $password 唯一标示
     * @param  string $new_pass 唯一标示
     */
    public function update_pass()
    {

        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];

        // 获取参数
        $user_id = Request::instance()->param('user_id');
        $password = Request::instance()->param('password', '', 'mcs');
        $new_pass = Request::instance()->param('new_pass', '', 'mcs');

        if (empty($user_id) || empty($password) || empty($new_pass)) throw new Exception('not Empty');

        $model = new MemberModel();

        // 查看老密码是否正确
        $find = $model->where(['id' => $user_id, 'password' => $password])->value('id');

        if (!empty($find)) {

            $pass = $model->where(['pay_pass' => $new_pass, 'id' => $user_id])->find();

            if (!empty($pass)) return ['code' => 402, 'message' => '支付密码不能跟登录密码相同,请重新输入'];

            // 验证数据
            $result = Db::name('member')->where(['id' => $user_id])->update(['password' => $new_pass]);

            if ($result) {
                return ['code' => 200, 'message' => '成功'];
            }

            return ['code' => 401, 'message' => '网络繁忙'];

        }

        return ['code' => 401, 'message' => '密码错误'];

    }

    /*
     * 商家端 - 修改绑定手机号
     * @param  string $phone        手机号
     * @param  string $code         验证码
     * @param  string $new_phone    新手机号
     * @param  string $new_code     新验证码
     */
    public function update_phone()
    {

        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];

        // 获取参数
        $data = Request::instance()->param();

        if (empty($data['phone']) || empty($data['new_phone']) || empty($data['code']) || empty($data['new_code'])) throw new Exception('not Empty');

        // 提交数据
        $model = new MemberModel();

        // 手机号是否存在
        $id = $model->where(['username' => $data['phone']])->value('id');

        if (empty($id)) return ['code' => 402, 'message' => '手机号不存在'];

        // 手机号是否存在
        $new_id = $model->where(['username' => $data['new_phone']])->value('id');

        if (!empty($new_id)) return ['code' => 402, 'message' => '手机号已存在'];

        // 判断验证码是否正确
        $smsVerify = Cache::get('sms_verify_find_' . $data['phone']);

        if ($smsVerify != $data['code']) {
            return ['code' => 401, 'message' => '原手机号验证码错误'];
        }

        // 判断验证码是否正确
        $new_smsVerify = Cache::get('sms_verify_reg_' . $data['new_phone']);

        if ($new_smsVerify != $data['new_code']) {
            return ['code' => 401, 'message' => '新手机号验证码错误'];
        }

        // 更新数据
        $result = $model->save(['username' => $data['new_phone']], ['username' => $data['phone']]);

        if ($result) {
            return ['code' => 200, 'message' => '成功'];
        }

        return ['code' => 401, 'message' => '网络繁忙'];

    }

    /*----------------------------------------------------------------------------------------------------------------------------------------------------
     * 商家端 - 短信验证码
     * @param  string $phone    手机号
     * @param  string $type     分类
     */
    public function get_code()
    {

        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];

        $phone = Request::instance()->param('phone');
        $type = Request::instance()->param('type');

        $user_id = MemberModel::where(['username' => $phone])->value('id');

        if ($type == 'reg' && !empty($user_id)) {

            // 注册获取验证码
            return ['code' => 402, 'message' => '用户已注册'];

        } elseif ($type == 'find' && empty($user_id)) {

            // 找回密码获取验证码
            return ['code' => 402, 'message' => '用户未注册'];

        } elseif ($type == 'update' && empty($user_id)) {

            // 修改密码
            return ['code' => 402, 'message' => '用户未注册'];

        }

        $smsVerify = Cache::get('sms_verify_' . $type . '_time_' . $phone);

        if (!empty($smsVerify)) {
            return ['code' => 401, 'message' => '60s内只能发送一次'];
        }

        $code = rand(100000, 999999);

        $content = '您好,您的短信验证码为：' . $code;

        $result = sendSMS($phone, $content);

        if ($result) {
            Cache::set('sms_verify_' . $type . '_time_' . $phone, $code, 60); // 短信请求有效期
            Cache::set('sms_verify_' . $type . '_' . $phone, $code, 900);     // 短信保存有效期
            return ['code' => 200, 'message' => '发送成功', 'data' => ['code' => $code, 'phone' => $phone]];
        }

        return ['code' => 400, 'message' => '网络繁忙'];
    }


    /**
     * 检查更新
     */
    public function check_update()
    {

        $data = Request::instance()->param('versions');

        $versions = (int)Db::name('Config')->where('varname','web_business_version')->value('varvalue');

        $url = "http://a.app.qq.com/o/simple.jsp?pkgname=com.lc.distribution.shop";

        //是否强制更新
        // if ($versions['force'] == 0) {

        if ($data == $versions) {
            return ['code' => 403, 'message' => '无需更新'];
        } else {
            return ['code' => 200, 'message' => '可以更新', 'url' => $url];
        }
        // } else {
        //     return ['code' => 200, 'message' => '强制更新', 'url' => $url];
        // }


    }
}
